package com.uduemc.biso.node.web.api.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.extities.center.SysContainerType;
import com.uduemc.biso.core.utils.RedisUtil;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.web.api.service.ContainerTypeService;
import com.uduemc.biso.node.web.component.CenterFunction;

@Service
public class ContainerTypeServiceImpl implements ContainerTypeService {

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private CenterFunction centerFunction;

	@Override
	public ArrayList<SysContainerType> getInfos()
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		String KEY = globalProperties.getRedisKey().getContainerType();
		@SuppressWarnings("unchecked")
		ArrayList<SysContainerType> cache = (ArrayList<SysContainerType>) redisUtil.get(KEY);
		if (CollectionUtils.isEmpty(cache)) {
			ArrayList<SysContainerType> data = centerFunction.getAllSysContainerType();
			if (redisUtil.set(KEY, data, 3600 * 24 * 10L)) {
				return data;
			} else {
				return null;
			}
		}
		return cache;
	}

	@Override
	public SysContainerType getInfoById(long id)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (id < 1) {
			return null;
		}
		ArrayList<SysContainerType> infos = getInfos();
		ArrayList<SysContainerType> items = (ArrayList<SysContainerType>) infos.stream().filter(item -> {
			return item.getId() != null && item.getId().longValue() == id;
		}).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(items)) {
			return null;
		}
		return items.get(0);

	}

}
